<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wechat:campUser:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wechat:campUser:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wechat:campUser:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wechat:campUser:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="campUserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="UUID" align="center" prop="userId" />
      <el-table-column label="微信id" align="center" prop="openId" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="用户头像" align="center" prop="imageUrl" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="密码" align="center" prop="password" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wechat:campUser:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wechat:campUser:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleWS(scope.row)"
            v-hasPermi="['wechat:campUser:remove']"
          >
            <el-badge :value="scope.row.count" class="item">
              <el-button size="small">聊天</el-button>
            </el-badge>
          </el-button>
        </template>

      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 与用户聊天对话框 -->
    <el-dialog :title="title1" :visible.sync="open1" width="500px" append-to-body>
      <el-table v-loading="loading" :data="onlineList" >
        <el-table-column label=""  prop="content"  >
          <template slot-scope="scope">
            <p align="right" v-if="scope.row.senderId==form1.senderId">{{scope.row.content}}</p>
            <p align="left" v-if="scope.row.senderId!=form1.senderId">{{scope.row.content}}</p>
          </template>
        </el-table-column>
      </el-table>

      <el-form ref="form1" :model="form1" :rules="rules1" label-width="80px">
        <el-form-item label="消息" prop="content">
          <el-input v-model="form1.content" placeholder="请输入消息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">发 送</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改微信用户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="微信id" prop="openId">
          <el-input v-model="form.openId" placeholder="请输入微信id" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="用户头像" prop="imageUrl">
          <el-input v-model="form.imageUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCampUser, getCampUser, delCampUser, addCampUser, updateCampUser } from "@/api/camp/campUser";
import { listOnline,updateOnline } from "@/api/camp/online";

export default {
  name: "CampUser",
  dicts: ['c_online_service_state'],
  data() {
    return {
      //聊天记录
      onlineList:[],
      // 弹出层标题
      title1: "",
      // 是否显示弹出层
      open1: false,
      // 表单参数
      form1: {
        senderId:""
      },
      //聊天列表
      wsList:[],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 微信用户管理表格数据
      campUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        phone: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "UUID不能为空", trigger: "blur" }
        ],
        openId: [
          { required: true, message: "微信id不能为空", trigger: "blur" }
        ],
      },
      // 表单校验
      rules1: {
        userId: [
          { required: true, message: "用户id不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "消息不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    console.log("userId:",this.$store.state.user)

    this.getList();
  },
  mounted() {
    //监听推送事件
    window.addEventListener("onmessageWS",(e)=>{
      this.onlineList.push(JSON.parse(e.detail.data))
      console.log("后台推送："+e.detail.data)
    })
  },
  methods: {
    /** 查询客服消息列表：未读的消息 */
    getOnlineList(senderId) {
      listOnline({"senderId":senderId,"state":0}).then(response => {
        this.onlineList = response.rows;

        for (let i = 0; i < this.onlineList.length; i++) {
          //更新未读的聊天记录
          updateOnline({messageId:this.onlineList[i].messageId,state:1}).then(response => {
            console.log("客服消息状态更新成功")
          });
        }

      });
    },
    //发送消息的方法
    async send(){
      var msg={
        "senderId":this.$store.state.user.id,
        "content":this.form1.content,
        "receiverId":this.form1.receiverId
      }
      //JSON.stringify(this.form1)
      this.$webSocket.sendWebSocket(JSON.stringify(msg))
      let online = {
        senderId:this.form1.senderId,
        content:this.form1.content
      }
      this.onlineList.push(online)
      this.form1.content = ""
    },
    //初始化websocket
    async initWebSocket(){
      this.onlineList = []
      this.$webSocket.initWebSocket()
    },
    //打开聊天对话框
    handleWS(data){
      this.reset1();
      this.open1 = true;
      this.title1 = data.username;
      this.form1.receiverId = data.userId;
      //查询未读的聊天记录
      this.getOnlineList(this.form1.receiverId)

      //重新聊天列表：wsList
      this.initWebSocket()
    },
    /** 提交按钮 */
    submitForm1() {
      this.$refs["form1"].validate(valid => {
        if (valid) {
          this.send();
        }
      });
    },
    // 取消按钮
    cancel1() {
      this.reset1()
      this.$webSocket.close()
    },
    reset1(){
      this.open1 = false;
      this.form1 = {
        receiverId:null,
        content: null,
      };
      this.resetForm("form1");
    },



    /** 查询微信用户管理列表 */
    getList() {
      this.loading = true;
      listCampUser(this.queryParams).then(response => {
        this.campUserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        openId: null,
        username: null,
        imageUrl: null,
        phone: null,
        password: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加微信用户管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids
      getCampUser(userId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改微信用户管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            updateCampUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCampUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除微信用户管理编号为"' + userIds + '"的数据项？').then(function() {
        return delCampUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wechat/campUser/export', {
        ...this.queryParams
      }, `campUser_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.item {
  margin-top: 10px;
  margin-right: 40px;
}</style>
